# BiocManager::install("treeio")
# BiocManager::install("ggtree")
library(treeio)
library(ggtree)
library(ggplot2) # to pre-build the plot
library(DescTools) # easy checking if ranges overlap
#
tree <- treeio::read.newick("C:/Users/ptx4/Desktop/example.data.for.testing/1504MLEXH-1/1504MLEXH-1.dnd")
tree_plot <-
ggtree::ggtree(tree) +
ggtree::geom_tiplab() +
ggplot2::xlim(NA, 0.02)
tip_vectorAll<-c()
#
# print(tip_vector)
#
# tip_vector <-
# list(
# c("2015C-3893_fastx5", "PNUSAE000514_fastx5"),
# c(
# "2015C-3893_fastx5",
# "PNUSAE000514_fastx5",
# "PNUSAE000632_fastx5"
# )
# )
# print(tip_vector)
tip_vector <-list(c("2015C-3893_fastx5", "PNUSAE000514_fastx5"))
tip_vector2 <-list(c("2015C-3893_fastx5", "PNUSAE000514_fastx5", "PNUSAE000632_fastx5"))
make_layer <- function(tree, tips, label, color, offset) {
ggtree::geom_cladelabel(
node = phytools::findMRCA(ape::as.phylo(tree), tips),
label = label,
color = color,
angle = 0,
offset = offset
)
}
check_overlap <- function(previous_plot, incoming_tips) {
pre_g <- ggplot2::ggplot_build(previous_plot)
tip_labels <- pre_g$data[[3]]
incoming_y_coords <-
tip_labels[tip_labels$label %in% incoming_tips, "y"]
# print(incoming_y_coords <-
# tip_labels[tip_labels$label %in% incoming_tips, "y"]
# )
if (length(pre_g$data) < 4) {
any_overlap <- FALSE
} else {
clade_segments <- pre_g$data[[4]]
#print(clade_segments <- pre_g$data[[4]])
overlaps <- sapply(1:nrow(clade_segments), function(i) {
X <- DescTools::Overlap(
x = c(clade_segments[i, "y"], clade_segments[i, "yend"]),
y = incoming_y_coords)
Y <- X > 0
#return(Y)
})
#print(overlaps)
#any_overlap <- any(overlaps)
}
#return(any_overlap)
}
#tip_vectorAll <- c(tip_vectorAll, tip_vector2)
add_annotations <- function(tree_plot, tip_vector) {
g <- tree_plot
#print(g$data)
for (i in seq_along(tip_vector)) {
#print(tip_vectorAll)
#print(tip_vector)
#tip_vector[i] <- tip_vector[i]
any_overlap <- check_overlap(previous_plot = g, incoming_tips = tip_vector[[i]])
print(tip_vector[[i]])
# current_offset <- ifelse(any_overlap, 0.011, 0.008)
print(any_overlap)
#print(current_offset)
g <- g +
make_layer(
tree_plot,
tips = tip_vector[[i]],
label = paste("Clade", i),
color = rev(colors())[i],
offset = current_offset <- ifelse(any_overlap, 0.011, 0.008)
)
}
return(g)
}
for (i in 1:length(tip_vector))
tip_vectorAll <- c(tip_vectorAll, tip_vector)
print(tip_vectorAll)
add_annotations(tree_plot = tree_plot, tip_vector = tip_vectorAll)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.